package com.market.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.market.auto.JSONAuthentication;
import com.market.entity.MaStall;
import com.market.entity.MaUser;
import com.market.mapper.MaStallMapper;
import com.market.mapper.MaUserMapper;
import com.market.response.Result;
import com.market.utils.UpPhotoNameUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author market
 * @since 2022-02-28
 */
@RestController
@RequestMapping("/ma-stall")
public class MaStallController extends JSONAuthentication {
    @Autowired
    MaStallMapper maStallMapper;
    @Autowired
    MaUserMapper maUserMapper;
    @ApiOperation(value = "添加摊位")
    @PostMapping("/add")
    public void addUser(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @RequestParam("price") float price,@RequestParam("stName") String stName) throws  Exception{
        MaStall maStall=new MaStall();
        maStall.setPrice(price);
        Date date=new Date();
        Timestamp timestamp=new Timestamp(date.getTime());
        maStall.setCreatTime(timestamp);
        maStall.setStName(stName);
        byte[] bytes = file.getBytes();
        String imageFileName = file.getOriginalFilename();
        String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
        Path path = Paths.get("D:\\自己的项目\\流浪动物救助\\adopt\\adopt\\src\\assets\\picture\\" + fileName);
        //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
        Files.write(path, bytes);//写入文件
        String avatar_url=fileName;
        maStall.setPicture(avatar_url);
        response.reset();

        if(maStallMapper.insert(maStall)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        }else{
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "删除摊位")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id ) throws Exception{
        int i=maStallMapper.deleteById(id);
        if(i>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "修改摊位名字")
    @PostMapping("/updStallName")
    public void updStallName(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int  id,@RequestParam("stName") String stName)throws Exception{
        MaStall maStall = maStallMapper.selectById(id);
        maStall.setStName(stName);
        if(maStallMapper.updateById(maStall)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "修改摊位价格")
    @PostMapping("/updStallPrice")
    public void updStallPrice(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int  id,@RequestParam("price") float price)throws Exception{
        MaStall maStall = maStallMapper.selectById(id);
        maStall.setPrice(price);
        if(maStallMapper.updateById(maStall)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找所有摊位")
    @PostMapping("/findAllStall")
    public void findAllStall(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        Page<MaStall> shUserPage=new Page<>(current,size);
        Page<MaStall> shUserPages=maStallMapper.selectPage(shUserPage,null);
        List<MaStall> records = shUserPages.getRecords();
        int total=maStallMapper.selectCount(null);
        if(records.size()>0){
            Result ok = Result.ok().data("stall",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "通过名字查找摊位")
    @PostMapping("/findByName")
    public void findByName(HttpServletRequest request, HttpServletResponse response,@RequestParam("stName") String  stName,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.like("st_name",stName);
        Page<MaStall> shUserPage=new Page<>(current,size);
        Page<MaStall> shUserPages=maStallMapper.selectPage(shUserPage,wrapper);
        List<MaStall> records = shUserPages.getRecords();
        int total=maStallMapper.selectCount(wrapper);
        if(records.size()>0){
            Result ok = Result.ok().data("stall",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "租用摊位")
    @PostMapping("/RentStall")
    public void RentStall(HttpServletRequest request, HttpServletResponse response,@RequestParam("userId") int  userId,@RequestParam("id") int id)throws  Exception{
        MaUser maUser=maUserMapper.selectById(userId);
        MaStall maStall=maStallMapper.selectById(id);
       if(maStall.getStatus()=="已租用"){
           Result error = Result.error().message("摊位已租用");
           this.WriteJSON(request, response, error);
       }else{
           float balance=maUser.getBalance();
           float price=maStall.getPrice();
           if(balance>price){
               maUser.setBalance(balance-price);
               maStall.setUserId(maUser.getId());
               maStall.setStatus("已租用");
               if(maUserMapper.updateById(maUser)>0&&maStallMapper.updateById(maStall)>0){
                   Result ok = Result.ok().message("成功租用");
                   this.WriteJSON(request, response, ok);
               }else{
                   Result error = Result.error().message("租用失败");
                   this.WriteJSON(request, response, error);
               }

           }else{
               Result error = Result.error().message("余额不足");
               this.WriteJSON(request, response, error);
           }
       }

    }
    @ApiOperation(value = "查找所有未租用摊位摊位")
    @PostMapping("/findAllStallNo")
    public void findAllStallNo(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("status","未租用");
        Page<MaStall> shUserPage=new Page<>(current,size);
        Page<MaStall> shUserPages=maStallMapper.selectPage(shUserPage,wrapper);
        List<MaStall> records = shUserPages.getRecords();
        int total=maStallMapper.selectCount(wrapper);
        if(records.size()>0){
            Result ok = Result.ok().data("stall",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
}

